package com.hiray.wanandroid.ui

import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.net.http.SslError
import android.os.Build
import android.text.TextUtils
import android.view.ViewGroup
import android.webkit.*
import androidx.annotation.DrawableRes
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.material.Colors
import androidx.compose.material.Icon
import androidx.compose.material.LinearProgressIndicator
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import com.hiray.wanandroid.BuildConfig
import com.hiray.wanandroid.R

class WebViewModel : ViewModel() {
    var title by mutableStateOf("加载中...")
    var progress by mutableStateOf(0)
}
@SuppressLint("SetJavaScriptEnabled")
@Composable
fun Web(navController: NavHostController, url: String) {
    val viewModel: WebViewModel = viewModel()
    Column(
        Modifier
            .fillMaxSize()
            .background(Color.White)) {
        TitleBar(title = viewModel.title, onBack = {
            navController.popBackStack()
        })
        Box(Modifier.fillMaxSize()) {
            AndroidView({ context ->
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                    WebView.setDataDirectorySuffix(BuildConfig.APPLICATION_ID)
                }
                WebView(context).apply {
                    layoutParams = ViewGroup.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.MATCH_PARENT
                    )
                    settings.apply {
                        domStorageEnabled = true
                        databaseEnabled = true
                        setAppCacheEnabled(true)
                        setAppCachePath(context.cacheDir.absolutePath)
                        allowFileAccess = false
                        savePassword = false
                        javaScriptEnabled = true
                        mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
                    }
                    webViewClient = object : WebViewClient() {
                        override fun shouldOverrideUrlLoading(
                            view: WebView?,
                            url: String?
                        ): Boolean {
                            if (url == null) {
                                return false
                            }

                            if (url.startsWith("http://", true)
                                || url.startsWith("https://", true)
                                || url.startsWith("ftp://", true)
                            ) {
                                view?.loadUrl(url)
                            } else {
                                val uri = Uri.parse(url)
                                if (!TextUtils.isEmpty(uri.scheme) && !TextUtils.isEmpty(uri.host)) {
                                    val intent = Intent(Intent.ACTION_VIEW, uri)
                                    if (isInstall(intent)) {
                                        try {
                                            context.startActivity(intent)
                                        } catch (e: Exception) {
                                        }
                                    }
                                }
                            }

                            return true
                        }

                        override fun onReceivedSslError(
                            view: WebView?,
                            handler: SslErrorHandler?,
                            error: SslError?
                        ) {
                            handler?.proceed()
                        }

                        private fun isInstall(intent: Intent): Boolean {
                            return context.packageManager.queryIntentActivities(
                                intent,
                                PackageManager.MATCH_DEFAULT_ONLY
                            ).size > 0
                        }
                    }
                    webChromeClient = object : WebChromeClient() {
                        override fun onReceivedTitle(view: WebView?, title: String?) {
                            viewModel.title = title ?: ""
                        }

                        override fun onProgressChanged(view: WebView?, newProgress: Int) {
                            super.onProgressChanged(view, newProgress)
                            viewModel.progress = newProgress
                        }
                    }
                    loadUrl(url)
                }
            }, Modifier.fillMaxSize())
            if (viewModel.progress < 100) {
                LinearProgressIndicator(
                    progress = viewModel.progress / 100f,
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(2.dp),
                    backgroundColor = Color.Transparent
                )
            }
        }
    }
}
@Composable
fun TitleBar(
    title: String,
    onBack: (() -> Unit)? = null,
    @DrawableRes icon: Int? = null,
    onIconClick: (() -> Unit)? = null,
) {
    Row(
        Modifier
            .fillMaxWidth()
            .height(48.dp)
            .background(Color.LightGray)
    ) {
        if (onBack != null) {
            Icon(
                modifier = Modifier
                    .align(alignment = Alignment.CenterVertically)
                    .clickable {
                        onBack.invoke()
                    }
                    .size(48.dp)
                    .padding(14.dp),
                painter = painterResource(id = R.drawable.back_to_top),
                contentDescription = "返回",
                tint = Color.DarkGray
            )
        }
        Text(
            text = title,
            modifier = Modifier
                .align(alignment = Alignment.CenterVertically)
                .padding(start = 16.dp, end = 16.dp)
                .weight(1f),
            color = Color.Black,
            fontSize = 17.sp,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis
        )
        if (icon != null) {
            Icon(
                modifier = Modifier
                    .align(alignment = Alignment.CenterVertically)
                    .clickable {
                        onIconClick?.invoke()
                    }
                    .size(48.dp)
                    .padding(14.dp),
                painter = painterResource(id = icon),
                contentDescription = "",
            )
        }
    }
}